import {Component, OnInit, AfterViewInit, HostListener} from '@angular/core';

import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ'
import {ActivatedRoute, ParamMap} from '@angular/router';
import {HttpService} from '@kylin/http';
import {HomeService} from '../home.service';
import {fromLonLat, transform} from 'ol/proj';
import {Attribution, defaults, ScaleLine} from 'ol/control'

import {FrontPageService} from './front-page.service';
import {WKT} from 'ol/format';
import {getCenter} from 'ol/extent';

// import {Tile} from 'ol';
// import {Fill, Stroke, Style} from 'ol/style';
// import {GeoJSON} from 'ol/format';
// import {Vector as VectorSource} from 'ol/source';
// import {Vector as VectorLayer} from 'ol/layer';
// import OSM from 'ol/source/OSM';
// import Overlay from 'ol/Overlay';

@Component({
    templateUrl: './front-page.component.html',
    styleUrls: ['./front-page.component.less']
})

export class FrontPageComponent implements OnInit, AfterViewInit {
    map: Map;
    switchLayerMenu = false;
    administrativeLayerMenu = false;
    administrativeLayerButtons = {province: false, city: false, counties: false};
    layers = {};
    hasMapLegend = false;
    hasMapLegendButton = true;
    utilsData = null;
    isFullscreen = true;
    layersPanelState = false;
    locationLonLat = null;

    constructor(private activatedRoute: ActivatedRoute,
                private http: HttpService,
                private homeService: HomeService,
                private frontPageService: FrontPageService
    ) {

    }

    ngOnInit() {
        this.init();
        this.turnOnByParams();
        this.frontPageService.layersObservable.subscribe(data => {
            this.layersPanelState = true;
        });
        this.frontPageService.LocationLonLatObservable.subscribe((layerId: any) => {
            this.fetchLayerCenter(layerId);
        });
    }

    fetchLayerCenter(layerId: string) {
        this.http.get('/layer/getDataByAttr', {layerId: layerId, attrList: ''})
            .then(res => {
                const the_geom = res.data.list[0].the_geom;
                this.locationLonLat = this.getFeatureCenter(the_geom);
            })
            .catch(err => {

            })
    }

    private getFeatureCenter(data: any): number[] {
        const olFeature = new WKT().readFeature(data);
        const extent = olFeature.getGeometry().getExtent();
        return getCenter(extent);
    }

    ngAfterViewInit(): void {

    }

    layersPanel(state: boolean) {

    }

    layersPanelStateChange($event) {
        this.layersPanelState = $event;
    }


    fullscreenButtonClick() {
        this.isFullscreen = !this.isFullscreen;
        this.homeService.$changeFullscreenObservable(this.isFullscreen);
    }

    private init() {
        const scaleLineControl = new ScaleLine({
            // 设置度量单位为米
            units: 'metric',
            target: 'scalebar',
            className: 'ol-scale-line'
        });

        this.map = new Map({
            layers: [
                new TileLayer({
                    source: new XYZ({
                        crossOrigin: 'anonymous',
                        url: `http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}`
                    })
                })
            ],
            target: 'map',
            view: new View({
                zoom: 4,
                center: fromLonLat([108.943904, 34.319323])
            }),
            controls: defaults({attribution: false, zoom: false, rotate: false})
        });

        // this.map.addControl(new FullScreen());
        this.map.addControl(new Attribution());
        this.map.addControl(scaleLineControl);

    }

    rotateNorth() {
        const viewAnimate = this.map['getView']();
        viewAnimate.animate({
            rotation: viewAnimate.getRotation() + Math.PI / 2
        })
    }

    switchLayer(type = 'default') {
        const layers = {
            default: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
            satellite: 'http://www.google.cn/maps/vt?lyrs=s@189&gl=cn&x={x}&y={y}&z={z}',
            topographic: 'http://www.google.cn/maps/vt/pb=!1m4!1m3!1i{z}!2i{x}!3i{y}!2m3!1e0!2sm!3i380072576!3m8!2szh-CN!3scn!5e1105!12m4!1e68!2m2!1sset!2sRoadmap!4e0!5m1!1e0'
        };
        const baseLayer = this.map.getLayers().item(0);
        baseLayer['setSource'](
            new XYZ({
                crossOrigin: 'anonymous',
                url: layers[type] || layers['default']
            })
        )
    }

    administrativeLayer($event, type: string) {
        const types = {
            province: 'http://121.41.65.118:8089/MapService/getGdp?x={x}&y={y}&z={z}&s=1',
            city: 'http://121.41.65.118:8089/MapService/getGdp?x={x}&y={y}&z={z}&s=2',
            counties: 'http://121.41.65.118:8089/MapService/getGdp?x={x}&y={y}&z={z}&s=3'
        };
        if ($event) {
            this.addLayer(type, types[type], {opacity: 1});
        } else {
            this.removeLayer(type);
        }
    }

    private addLayer(name: string, url: string, options?: { opacity: number }) {
        if (this.layers[name]) {
            return;
        }
        this.layers[name] = new TileLayer({
            source: new XYZ({
                crossOrigin: 'anonymous',
                url: url
            }),
            opacity: options.opacity || 1
        });
        this.map.addLayer(this.layers[name]);
    }

    private removeLayer(name: string) {
        if (this.layers[name]) {
            this.map.removeLayer(this.layers[name]);
            delete this.layers[name];
        }
    }

    mapLegendClose($event) {
        this.hasMapLegend = $event;
        this.hasMapLegendButton = true;
    }

    turnOnByParams() {
        this.activatedRoute.queryParams.subscribe((params: ParamMap) => {
            this.utilsData = params;
        })
    }

    location() {
        if (this.locationLonLat) {
            this.map.getView().animate({center: this.locationLonLat}, {zoom: 8});
        } else {
            this.map.getView().animate({center: transform([108.943904, 34.319323], 'EPSG:4326', 'EPSG:3857')}, {zoom: 4});
        }
    }

    changeZoom(type: 'plus' | 'minus') {
        let currentZoom = this.map.getView().getZoom();
        type === 'plus' ? currentZoom += 1 : currentZoom -= 1;
        this.map.getView().animate({zoom: currentZoom});
    }
}
